import { MacroAction } from "@/src/types/types";
import { eventCode2Keycode } from "./keycode";
import { shiftFrom16Bit, shiftTo16Bit } from "@/src/devices/KeyboardAPI";
import keyInfoJson from "@/src/config/keyinfos.json";

// export type MacroAction = {
//     name: string,   //显示名称
//     code: number,   //按键值
//     type: number,   // 1 鼠标， 2 键盘
//     action: number, // 1 按下 2 松开
//     time?: number,
//     delay?: number  //延时
// }

// export type Macro = {
//     name: string,
//     list: MacroAction[]
// }

const codeMouseName = ['Mouse L-Button', 'Mouse M-Button', 'Mouse R-Button', 'Mouse Backward', 'Mouse Forward'];

const getName = (code: number, type: number) => {

    if (type == 1) {
        return codeMouseName[code];
    } else {
        const key = keyInfoJson.keyInfos.find((keyInfo) => keyInfo.value1 == code)
        return key?.name || code + '';
    }
}

// export const parseMacro = (macroData: number[], macroArr: MouseMacro[]) => {
//     let newMacroArr: MouseMacro[] = macroArr.map((macro, index) => {

//         if (macroData[index * 2] == 0xff && macroData[index * 2 + 1] == 0xff) {
//             return macro;
//         }
//         if (macroData[index * 2] == 0x0) {
//             return macro;
//         }

//         let offset = shiftTo16Bit([macroData[index * 2], macroData[index * 2 + 1]]);

//         if (offset > 4096) {
//             return macro;
//         }

//         let end = false
//         let list = [];
//         do {
//             const delay = shiftTo16Bit([macroData[offset], macroData[offset + 1]]);
//             console.log(macroData[offset + 2]);
//             let type = 0x01; // 鼠标
//             if ((macroData[offset + 2] & 0b111111) == 2) {
//                 type = 0x02;
//             } else if ((macroData[offset + 2] & 0b111111) == 4) {
//                 type = 0x03; // 滚轮
//             }
//             // const type = macroData[ offset+2] >> 1 & 0x1 ? 2 : 1;
//             const action = macroData[offset + 2] >> 6 & 0x1 ? 1 : 2;
//             const code = macroData[offset + 3];
//             list.push({
//                 name: getName(code, type),
//                 code,
//                 type,
//                 action,
//                 delay
//             })
//             end = (macroData[offset + 2] >> 7 & 0x1 ? true : false) || macroData[offset + 2] == 0;
//             offset += 4;
//         }
//         while (!end)

//         return {
//             ...macro,
//             list
//         };
//     });

//     return newMacroArr;
// }

// 获取宏数据
export const getMacroData = (keyIndex: number, type: number, delayTime: number, actionArr: MacroAction[]) => {
    let actionOffset = 3;
    let actionBytes: number[] = [];
    actionBytes[0] = keyIndex;
    actionBytes[1] = actionArr.length;
    actionBytes[2] = 0x01 | delayTime;
    if (type == 2) {
        actionBytes[2] = 0x81;
    }
    actionArr.map((actionItem: MacroAction, index: number) => {
        let code = actionItem.code;
        if (actionItem.action == 1 && type == 1) {
            code |= 1 << 7;
        }
        actionBytes[actionOffset + index] = code;
    });
    return actionBytes;
}

export const addMacroActionList = (actionList: MacroAction[], event: MouseEvent | KeyboardEvent | WheelEvent, time: number, delayTime: number, lastActionTime: number = 0) => {
    // console.log('event',event)
    const action = evtToAction(event);
    if (actionList.length > 0) {
        const lastAction = actionList.at(-1);
        if (lastAction !== undefined) {
            const newActionList = actionList.slice(0, -1);
            
            // 使用lastActionTime计算延迟
            let calculatedDelay = delayTime;
            if (delayTime < 0) { // 仅当使用实际时间间隔时进行特殊处理
                // 如果lastActionTime为0，则使用lastAction.time
                // 如果lastActionTime不为0，则使用lastActionTime
                const timeBase = lastActionTime > 0 ? lastActionTime : (lastAction.time || 0);
                calculatedDelay = time - timeBase;
                
                // 如果计算的延迟大于5秒，可能是长时间未操作或新一轮录制的第一个动作
                // 这种情况下将延迟限制为默认的100毫秒
                if (calculatedDelay > 5000 ) {
                    calculatedDelay = 5000; // 使用固定的100毫秒作为默认值
                } else if (calculatedDelay < 0 || !isFinite(calculatedDelay)) {
                    calculatedDelay = 100;
                }
            }
            
            const actions = [{
                ...lastAction, delay: delayTime >= 0 ? delayTime : calculatedDelay
            }, { ...action, time, delay: 0 }]
            
            if (newActionList.length > 0) {
                return [...newActionList, ...actions];
            } else {
                return actions;
            }
        } else {
            return [];
        }
    } else {
        return [{ ...action, time, delay: 0 }];
    }
}

export const evtToAction = (event: MouseEvent | KeyboardEvent | WheelEvent) => {
    if (event instanceof MouseEvent) {
        const mouseButtons = ['MS-L-Button', 'MS-M-Button', 'MS-R-Button', 'MS-Backward', 'MS-Forward'];
        let name = mouseButtons[event.button] || event.button + '';
        const code = event.button;
        const type = 1;
        let action = event.type == 'mousedown' ? 1 : 0;
        if (event.type === 'wheel' && event instanceof WheelEvent) {
            // action = 3
            if (event.deltaY > 0) {
                name = 'Wheel D-Scroll'
                action = 3
            } else if (event.deltaY < 0) {
                name = 'Wheel U-Scroll'
                action = 4
            }
        }

        return { name, code, type, action, time: 0, delay: 0 };
    } else {
        // 特殊处理空格键和其他可能没有正确显示名称的按键
        let name = '';
        if (event.code === 'Space') {
            name = 'Space';
        } else if (event.code === 'Enter') {
            name = 'Enter';
        } else if (event.code === 'Tab') {
            name = 'Tab';
        } else if (event.code === 'Escape') {
            name = 'Esc';
        } else if (event.code === 'Backspace') {
            name = 'Backspace';
        } else {
            // 默认使用key值，对于大多数按键这应该可以正常工作
            name = event.key.toUpperCase();
        }
        
        const code = eventCode2Keycode(event.code);
        const type = 2;
        const action = event.type == 'keydown' ? 1 : 0;
        return { name, code, type, action, time: 0, delay: 0 };
    }
}